package com.we.wfc.common.redisson;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 分布式锁实现类
 * @Author:Liangzy(Feeling)
 * @Date:Create in 2020/1/7 6:39 下午
 */
@Component
public class RedissonDistributedLocker implements DistributedLocker {

    private RedissonClient redissonClient;

    /**
     * @Description 获取锁实例
     **/
    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * @Description 加锁
     **/
    @Override
    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    /**
     * @Description 加带超时时间(单位秒)的锁
     **/
    @Override
    public RLock lock(String lockKey, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(leaseTime, TimeUnit.SECONDS);
        return lock;
    }

    /**
     * @Description 加锁，并设置超时时间及单位
     **/
    @Override
    public RLock lock(String lockKey, TimeUnit unit, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }

    /**
     * @Description 尝试加锁，并设置等待时间及锁超时时间
     **/
    @Override
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            // 修正 Either re-interrupt this method or rethrow the "InterruptedException".
            Thread.currentThread().interrupt();
            return false;
        }
    }

    /**
     * @Description 检查此锁被任何线程锁定
     **/
    @Override
    public boolean isLocked(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        return lock.isLocked();
    }

    /**
     * @Description 释放锁
     **/
    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    /**
     * @Description 释放锁对象
     **/
    @Override
    public void unlock(RLock lock) {
        lock.unlock();
    }
}
